package com.sbring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class SbringApplicationContext {

    private Class configClass;
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>(); // 单例池
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<BeanPostProcessor>();

    public SbringApplicationContext(Class configClass) {
        this.configClass = configClass;

        // 解析配置类
        // 获得ComponentScan注解，及其扫描路径--> 扫描带有注解的类 --> beanDefinitionMap
        scan(configClass);

        // 创建单例bean
        for(String beanName: beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName,beanDefinition);
                singletonObjects.put(beanName,bean);
            }
        }
    }

    private Object createBean(String beanName,BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getClazz();
        try {
            // 根据类型创建实例
            Object instance = clazz.getDeclaredConstructor().newInstance();

            // 对该类下的成员变量进行依赖注入
            for (Field field : clazz.getDeclaredFields()){
                if(field.isAnnotationPresent(Autowired.class)){
                    Object bean = getBean(field.getName());
                    field.setAccessible(true);
                    field.set(instance, bean);
                }
            }

            // aware回调
            if( instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            for (BeanPostProcessor bpp : beanPostProcessorList) {
                bpp.postProcessBeforeInitialization(instance, beanName);
            }

            // 初始化
            if( instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }

            for (BeanPostProcessor bpp : beanPostProcessorList) {
                bpp.postProcessAfterInitialization(instance, beanName);
            }

            return instance;
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private void scan(Class configClass) {
        // 获得路径
        ComponentScan componentScanAnnotation = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScanAnnotation.value();

        // 获得包
        // 获得包下的文件
        ClassLoader classLoader = SbringApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(path.replace(".", "/"));
        File file = new File(resource.getFile());
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for (File f :  files) {
//                System.out.println(f);
                String fileName = f.getAbsolutePath();
                if(fileName.endsWith(".class")) {
                    // 转成全类名的形式
                    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class")).replace("\\", ".");
                    try {
                        // 加载类
                        Class<?> clazz = classLoader.loadClass(className);
                        // 判断是否包含注解
                        if(clazz.isAnnotationPresent(Component.class)) {

                            // 判断当前class是否实现BeanPostProcessor接口
                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                // 得到BeanPostProcessor对象，进行保存
                                BeanPostProcessor instance = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
//                                BeanPostProcessor instance = (BeanPostProcessor) getBean(className);
                                beanPostProcessorList.add(instance);
                            }

                            Component componentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                            String beanName = componentAnnotation.value();

                            // 获得bean的定义
                            BeanDefinition beanDefinition = new BeanDefinition();

                            // 给beanDefinition赋值，扫描到的添加到beanDefinitionMap中
                            if (clazz.isAnnotationPresent(Scope.class)) {
                                Scope ScopeAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(ScopeAnnotation.value());
                            } else {
                                beanDefinition.setScope("singleton");
                            }

                            beanDefinition.setClazz(clazz);
                            beanDefinitionMap.put(beanName, beanDefinition);
                        }

                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                }

            }
        }
    }

    public Object getBean(String beanName){

        if(beanDefinitionMap.containsKey(beanName)) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            // 是单例就从单例池里面拿
            if(beanDefinition.getScope().equals("singleton")){
                return singletonObjects.get(beanName);
            } else {
                // 创建bean对象
                return createBean(beanName, beanDefinition);
            }
        } else {
            throw new NullPointerException("no such bean");
        }
    }

}
